package com.maycur.ctrip.mybatis.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by wangsenyuan on 3/9/16.
 */
@MappedTypes({Boolean.class, boolean.class})
public class BooleanTypeHandler extends BaseTypeHandler<Boolean> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
        throws SQLException {
        if (jdbcType == JdbcType.BOOLEAN || jdbcType == JdbcType.BIT) {
            setBoolean(ps, i, parameter);
        } else {
            setChar(ps, i, parameter);
        }
    }

    private void setChar(PreparedStatement ps, int i, Boolean parameter) throws SQLException {
        if (parameter != null && parameter) {
            ps.setString(i, "Y");
        } else {
            ps.setString(i, "N");
        }
    }

    private void setBoolean(PreparedStatement ps, int i, Boolean parameter) throws SQLException {
        if (parameter != null && parameter) {
            ps.setBoolean(i, true);
        } else {
            ps.setBoolean(i, false);
        }
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object val = rs.getObject(columnName);
        Boolean aBoolean = readAsStringPossible(val);
        if (aBoolean != null)
            return aBoolean;
        return rs.getBoolean(columnName);
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object val = rs.getObject(columnIndex);
        Boolean x = readAsStringPossible(val);
        Boolean aBoolean = readAsStringPossible(val);
        if (aBoolean != null)
            return aBoolean;
        return rs.getBoolean(columnIndex);
    }

    private Boolean readAsStringPossible(Object val) {
        if (val == null) {
            return false;
        }

        if (val instanceof String) {
            return "Y".equals(val);
        }

        return null;
    }

    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        throw new UnsupportedOperationException("");
    }
}
